package com.bst.common.utils.poi;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.bst.common.annotation.Excel;
import com.bst.common.annotation.Excels;
import com.bst.common.vo.HeaderAndBodyVO;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EasyExcelUtil<T> {
    public Class<T> clazz;

    public EasyExcelUtil(Class<T> clazz)
    {
        this.clazz = clazz;
    }
    /**
     * 导出类型（EXPORT:导出数据；IMPORT：导入模板）
     */
    private Excel.Type type;
    public void exportExcelForEntry(List<T> list, String sheetName, HttpServletResponse response) {
        setHeader(response);
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .inMemory(false) // 关键配置：禁用全内存模式，启用磁盘缓存
                .autoCloseStream(true) // 自动关闭流
                .useDefaultStyle(false) // 不使用默认样式减少内存
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自适应列宽
                .build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName)
                    .head(clazz) // 设置表头
                    .build();
            excelWriter.write(list, writeSheet);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    public void exportExcelForMay(HeaderAndBodyVO vo, String sheetName, HttpServletResponse response) {
        setHeader(response);

    }

    private void setHeader(HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=large_data.xlsx");
    }

}
